package thread.threadlocal;

import java.util.HashMap;
import java.util.Map;

public class MThreadLocal <T>{
	public void set(T t){
		MyThread mt = (MyThread) Thread.currentThread();
		ThreadLocalMap map = mt.threadlocals;
		if(map == null){
			mt.threadlocals = new ThreadLocalMap();
			map = mt.threadlocals;
		}
		map.set(this,t);
	}
	
	public T get(){
		MyThread mt = (MyThread) Thread.currentThread();
		ThreadLocalMap map = mt.threadlocals;
		return (T) map.get(this);
	}
	static class ThreadLocalMap{
		//用hashmap也不会出现线程安全问题，因为map是线程级别的
		private Map<MThreadLocal,Object> map = new HashMap<MThreadLocal,Object>();
		private Object get(MThreadLocal key){
			return map.get(key);
		}
		private void set(MThreadLocal key,Object value){
			map.put(key, value);
		}
	}
}
